package at.codebase.web.servlets.user;

import static at.codebase.web.util.i18n.I18NFactory.i18n;

import java.util.HashMap;

import at.codebase.core.log.Log;
import at.codebase.db.dao.EUserDao;
import at.codebase.db.entities.EUser;
import at.codebase.security.SecureStringBuilder;
import at.codebase.web.servlets.user.UserInputStatus.InputStatus;
import at.codebase.web.servlets.user.UserInputStatus.InputStatusDescription;
import at.codebase.web.servlets.user.UserInputStatus.InputStatusUsername;
import at.codebase.web.templates.ErrorWidget;
import at.codebase.web.templates.MainTemplate;
import at.codebase.web.templates.UserProfileTemplate;
import at.codebase.web.util.LocalRequest.RequestInformation;
import at.codebase.web.util.URLParameters.ParameterException;
import at.codebase.web.util.template.Template;
import at.codebase.web.util.template.TemplateEngine;

/**
 * 
 * @author Lukas Pfeifhofer <lukas.pfeifhofer@devlabs.pro>
 * 
 */
public class UserEdit extends AUserProfile {

	@Override
	@SuppressWarnings("rawtypes")
	void buildUserPage(MainTemplate mainTemplate,
			UserProfileTemplate userProfileTemplate,
			RequestInformation requestInfo, UserLevel level,
			RequestType requestType) {
		mainTemplate.setTitle(i18n(requestInfo.getLocale()).string(
				"userEdit_header"));

		EUser user = requestInfo.getUser();
		if (user != null) {
			if (requestType.equals(RequestType.POST)) {
				if(!tokenCorrect(requestInfo)) {
					processRequestNoAccess(requestInfo, level);
					return;
				}

				HashMap<String, InputStatus> inputStatusMap = new HashMap<String, InputStatus>();

				try {
					inputStatusMap.put("userUsername",
							new InputStatusUsername(requestInfo.getParameters()
									.getString("userUsername")));
				} catch (ParameterException e) {
					inputStatusMap.put("userUsername", new InputStatusUsername(
							null));
				}

				try {
					inputStatusMap.put(
							"userDescription",
							new InputStatusDescription(requestInfo
									.getParameters().getString(
											"userDescription")));
				} catch (ParameterException e) {
					inputStatusMap.put("userDescription",
							new InputStatusDescription(null));
				}

				boolean allValid = true;

				for (String key : inputStatusMap.keySet()) {
					InputStatus inputStatus = inputStatusMap.get(key);
					inputStatus.compile();
					if (inputStatus.isError())
						allValid = false;
				}

				if (allValid) {
					String userUsername = ((InputStatusUsername) inputStatusMap
							.get("userUsername")).getValue();
					String userDescription = ((InputStatusDescription) inputStatusMap
							.get("userDescription")).getValue();
					
					boolean usernameAlreadyExists;
					if(requestInfo.getUser().getUsername().equals(userUsername)){
						usernameAlreadyExists = false;
					}else{
						usernameAlreadyExists =EUserDao.duplicateUsername(userUsername); 
					}
					

					if (!usernameAlreadyExists) {
						user.setUsername(userUsername);
						user.setDescription(userDescription);

						EUserDao.saveUser(user);

						Log.logUser(
								requestInfo.getUser().getId(),
								new SecureStringBuilder()
										.appendInsecure("User (userid=")
										.appendInsecure(
												String.valueOf(user.getId()))
										.appendInsecure(
												") has changed his account")
										.toString());

						redirectTo("/user/profile");
					} else {
						buildPage(userProfileTemplate, requestInfo, user,
								inputStatusMap, usernameAlreadyExists);
					}
				} else {
					buildPage(userProfileTemplate, requestInfo, user,
							inputStatusMap, false);
				}
			} else {
				HashMap<String, InputStatus> inputStatusMap = new HashMap<String, InputStatus>();

				inputStatusMap.put("userUsername",
						new InputStatusUsername(user.getUsername()));
				inputStatusMap.put("userDescription",
						new InputStatusDescription(user.getDescription()));

				buildPage(userProfileTemplate, requestInfo, user,
						inputStatusMap, false);
			}
		}

	}

	@SuppressWarnings({ "rawtypes", "unused" })
	private void buildPage(UserProfileTemplate userProfileTemplate,
			RequestInformation requestInfo, EUser user,
			HashMap<String, InputStatus> inputStatusMap,
			boolean usernameAlreadyExists) {
		Template userEditT = TemplateEngine
				.getTemplate("user/site_profile_edit.html");

		// ErrorWidget
		ErrorWidget errorWidget = new ErrorWidget();
		if (inputStatusMap.get("userUsername").isError())
			errorWidget.addErrorItem(i18n(requestInfo.getLocale()).string(
					"userEdit_usernameError"));
		if (usernameAlreadyExists)
			errorWidget.addErrorItem(i18n(requestInfo.getLocale()).string(
					"userEdit_usernameExistsError"));
		if (inputStatusMap.get("userDescription").isError())
			errorWidget.addErrorItem(i18n(requestInfo.getLocale()).string(
					"userEdit_descriptionError"));

		if (errorWidget.hasErrors())
			userEditT.setTemplate("errorWidget", errorWidget);

		userEditT.setHTML(
				"userUsernameValue",
				new SecureStringBuilder().appendSecure(
						inputStatusMap.get("userUsername").getRawString())
						.toString());
		userEditT.setHTML(
				"userDescriptionValue",
				new SecureStringBuilder().appendSecure(
						inputStatusMap.get("userDescription").getRawString())
						.toString());
		
		userEditT.setText("randomKey", nextToken());

		userProfileTemplate.setContent(userEditT);
	}

}